using DevExpress.XtraEditors;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using  WinformDevelopFrame.Core.Extend;
using  WinformDevelopFrame.IServices;
using  WinformDevelopFrame.Entity;
using DevExpress.XtraEditors.Repository;
using WinformDevelopFrame.Common;
using WinformDevelopFrame.Core.Form;
using DevExpress.XtraTreeList.Nodes;
using SqlSugar.Extensions;
using WinformDevelopFrame.Services;
using DevExpress.ClipboardSource.SpreadsheetML;

namespace  WinformDevelopFrame.UI
{
    public partial class Frmsysrole : BaseForm
    {
        private ISqlSugarClient _sqlSugarClient;
        private IsysroleService _sysroleService;
        private ISysDataTableService _sysDataTableService;
        private IsysmenuService _sysmenuService;
        public  Frmsysrole(ISqlSugarClient sqlSugarClient, IsysroleService sysroleService,IsysmenuService sysmenuService,ISysDataTableService sysDataTableService)
        {
            _sqlSugarClient = sqlSugarClient;
            _sysroleService = sysroleService;
            _sysmenuService = sysmenuService;
            _sysDataTableService = sysDataTableService;
            InitializeComponent();
            Init();
        }

        public override void Form_Load()
        {
            InitListCol();

        }

        private void SetTreeList()
        {
            List<sysrolemenu> list = _sqlSugarClient.Queryable<sysrolemenu>().Where(p => p.RoleId == ID).ToList();
            foreach (TreeListNode treeList1Node in treeList1.Nodes)
            {
                if (list.Select(p => p.MenuId).Contains(treeList1Node.GetValue("Id").ObjToInt()))
                {
                    treeList1Node.Checked = true;
                }
                SetGN(treeList1Node, list);
            }
        }
        /// <summary>
        /// 设置list lookupedit 列
        /// </summary>
        private void InitListCol()
        {
            CreateUserId.Properties.NullText = "";
            gridView1.Columns["CreateUserId"].ColumnEdit = new RepositoryItemLookUpEdit()
            {
                Name = "repositoryItemLookUpEditCreateUserId",
                DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL),
                DisplayMember = "用户名称",
                ValueMember="Id"
            };
            UpdateUserId.Properties.NullText = "";
            gridView1.Columns["UpdateUserId"].ColumnEdit = new RepositoryItemLookUpEdit()
            {
                Name = "repositoryItemLookUpEditUpdateUserId",
                DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                    .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL),
                DisplayMember = "用户名称",
                ValueMember = "Id"
            };

        }
        //设置不可编辑
        private void SetReadOnlyField()
        {
            ReadOnlyList.Add("CreateUserId");
            ReadOnlyList.Add("CreateTime");
            ReadOnlyList.Add("UpdateUserId");
            ReadOnlyList.Add("UpdateTime");
        }
        /// <summary>
        /// 设置数据 设置列名
        /// </summary>
        private void Init()
        {
            fileds.Add("RoleName", "角色名称");
            fileds.Add("RoleCode", "角色编码");
            fileds.Add("CreateUserId", "创建人");
            fileds.Add("CreateTime", "创建时间");
            fileds.Add("UpdateUserId", "修改人");
            fileds.Add("UpdateTime", "修改时间");
            fileds.Add("Remark", "备注");
            SetReadOnlyField();
            var m = _sysmenuService.QueryByClause(p => p.MenuCode.Equals(this.Name));
            //获取工具按钮
            var menus=_sysmenuService.QueryListByClause(p=>p.PId==m.Id).OrderBy(p=>p.OrderNo).ToList();
            menus.ForEach(p =>
            {
                btns.Add(new SimpleButton()
                {
                    Text = p.MenuText,
                    Name = p.MenuCode,
                    Image = Image.FromFile(Application.StartupPath+p.MenuIcon)
                });
            });
            CreateUserId.Properties.DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL);
            CreateUserId.Properties.DisplayMember = "用户名称";
            CreateUserId.Properties.ValueMember = "Id";
            UpdateUserId.Properties.DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL);
            UpdateUserId.Properties.DisplayMember = "用户名称";
            UpdateUserId.Properties.ValueMember = "Id";

            treeList1.DataSource= _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("菜单-treelistLookupedit")).SQL);
            treeList1.KeyFieldName = "Id";
            treeList1.ParentFieldName = "PId";
            treeList1.RootValue = -1;
        }
        public override void SetGridData()
        {
            gridControl1.DataSource =_sysroleService.Query();
        }
        public override void InitToolBtnStatusFunction(FormStatus status, SimpleButton btn)
        {
            base.InitToolBtnStatusFunction(status,btn);
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns></returns>
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(RoleName.Text))
            {
                "角色名称不能为空".ShowTips();
                return false;
            }
            if (string.IsNullOrEmpty(RoleCode.Text))
            {
                "角色编码不能为空".ShowTips();
                return false;
            }
            return true;
        }
        public override void AddFunction()
        {
            CreateTime.DateTime=DateTime.Now;
            CreateUserId.EditValue = AppInfo.User.Id;
        }
        public override void GridControlDoubleClickFunction()
        {
            ID = ((sysrole)gridView1.GetRow(gridView1.FocusedRowHandle)).Id;
            SetTreeList();
        }
        public override void EditFunction()
        {
            UpdateTime.DateTime = DateTime.Now;
            UpdateUserId.EditValue = AppInfo.User.Id;
        }

        public override bool SaveFunction()
        {
            if (CheckData())
            {
                var nodes=treeList1.Nodes;
                RoleM m = new RoleM()
                {
                    Role = this.ControlDataToModel<sysrole>()
                };
                foreach (TreeListNode treeList1Node in treeList1.Nodes)
                {
                    if (treeList1Node.Checked)
                    {
                        sysrolemenu g = new sysrolemenu(){RoleId = m.Role.Id,MenuId = treeList1Node.GetValue("Id").ObjToInt()};
                        m.MenuList.Add(g);
                    }
                    GetGN(treeList1Node,m);
                }
                if ((FormStatus == FormStatus.Add))
                {
                    ID =_sysroleService.Add(m);
                    return ID>0;
                }
                else
                {
                    return _sysroleService.UpdateN(m);
                }
            }

            return false;
        }

        public override bool DeleteFunction()
        {
            RoleM m = new RoleM()
            {
                Role = this.ControlDataToModel<sysrole>()
            };
            return _sysroleService.DeleteN(m);
        }

        public override bool CancelFunction()
        {
            return base.CancelFunction();
        }
        //勾选|取消勾选 父节点，递归处理子节点
        private bool m_SetClick = true;
        private void SetSubNodeCheck(TreeListNode p_TreeNode, bool p_SelectCheck)
        {
            m_SetClick = false;
            foreach (TreeListNode _SubNode in p_TreeNode.Nodes)
            {
                _SubNode.Checked = p_SelectCheck;
                SetSubNodeCheck(_SubNode, p_SelectCheck);
            }
        }
        //勾选子节点，父节点同样勾上
        private void SetParentCheck(TreeListNode p_TreeNode)
        {
            if (p_TreeNode.Checked && p_TreeNode.ParentNode != null)
            {
                p_TreeNode.ParentNode.Checked = true;
                SetParentCheck(p_TreeNode.ParentNode);
            }
        }
        //如果当前分支下最后一个勾选的子节点取消勾选，父节点勾选状态取消
        private void SetParentNotCheck(TreeListNode p_TreeNode)
        {
            if (!p_TreeNode.Checked && p_TreeNode.ParentNode != null)
            {
                foreach (TreeListNode _Node in p_TreeNode.ParentNode.Nodes)
                {
                    if (_Node.Checked) return;
                }
                p_TreeNode.ParentNode.Checked = false;
                SetParentNotCheck(p_TreeNode.ParentNode);
            }
        }

        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            // 禁用TreeView视图重绘的功能。
            treeList1.BeginUpdate();
            if (m_SetClick)
            {
                SetSubNodeCheck(e.Node, e.Node.Checked);
                SetParentCheck(e.Node);
                SetParentNotCheck(e.Node);
                m_SetClick = true;
            }
            // 启用TreeView视图重绘的功能。
            treeList1.EndUpdate();
        }
        private void GetGN(TreeListNode root, RoleM m)
        {
            foreach (TreeListNode treeListNode in root.Nodes)
            {
                if (treeListNode.Checked)
                {
                    sysrolemenu g = new sysrolemenu(){RoleId = m.Role.Id};
                    g.MenuId = treeListNode.GetValue("Id").ObjToInt();
                    m.MenuList.Add(g);
                }
                if (treeListNode.HasChildren)
                {
                    GetGN(treeListNode, m);
                }
            }
        }
        private void SetGN(TreeListNode root, List<sysrolemenu> list)
        {
            foreach (TreeListNode treeListNode in root.Nodes)
            {
                if (list.Select(p => p.MenuId).Contains(treeListNode.GetValue("Id").ObjToInt()))
                {
                    treeListNode.Checked = true;
                }
                if (treeListNode.HasChildren)
                {
                    SetGN(treeListNode, list);
                }
            }
        }
    }
}